package com.lujianfei.productprice.ui.main;

import android.content.Intent;
import android.os.AsyncTask;

import com.lujianfei.productprice.ui.ShopDetail.ShopActivity;
import com.lujianfei.productprice.ui.addShop.AddShopActivity;

import java.util.List;

public class MainPresenter implements MainContract.Presenter {

    MainContract.View view;
    MainContract.Model model;

    public MainPresenter(MainContract.View view) {
        this.view = view;
        this.model = new MainModel();
    }

    @Override
    public void loadData() {
        if (model.hasScardImportFile()){
            new AsyncTask<Void,Void,Void>(){

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    view.showLoading();
                }

                @Override
                protected Void doInBackground(Void... voids) {
                    model.deleteOriginalData();
                    model.importDataFromFile();
                    model.deleteScardImportFile();
                    return null;
                }

                @Override
                protected void onPostExecute(Void aVoid) {
                    super.onPostExecute(aVoid);
                    view.hideLoading();
                    List<ShopEntity> list = model.loadData();
                    view.setData(list);
                }
            }.execute();
        }else {
            List<ShopEntity> list = model.loadData();
            view.setData(list);
        }
    }

    @Override
    public void openEdit(ShopEntity itemAtPosition) {
        Intent intent = new Intent(view.getContext(), AddShopActivity.class);
        intent.putExtra("id",itemAtPosition.getId());
        view.getContext().startActivity(intent);
    }

    @Override
    public void delete(ShopEntity itemAtPosition) {
        itemAtPosition.delete();
        loadData();
    }

    @Override
    public void showShop(ShopEntity itemAtPosition) {
        Intent intent = new Intent(view.getContext(), ShopActivity.class);
        intent.putExtra("id",itemAtPosition.getId());
        intent.putExtra("name",itemAtPosition.getShopName());
        view.getContext().startActivity(intent);
    }
}
